<?php
/**
 * Created by PhpStorm.
 * User: yuhaoyu
 * Date: 12/22/18
 * Time: 1:20 PM
 */

namespace App\Services;


use App\Repositories\UserRepository;

class UserService extends Service
{
    protected $user_repo;
    private $salt = 'U0sPaAC8';

    public function __construct(UserRepository $user) {
        $this->user_repo = $user;
    }

    public function login($info){
        if(!isset($info['username'])||!isset($info['password'])){
            return $this->message('1021','信息不完整');
        }
        $user_info = $this->user_repo->get_by_where(['username'=>$info['username']]);

        if($user_info==null)
            return $this->message('1022','用户不存在');

        if($user_info['username']==$info['username']&&$user_info['password']==$this->hash($info['password'])){
            $session_info=null;
            $session_info['id']=$user_info['id'];
            $session_info['username']=$user_info['username'];
            $session_info['name']=$user_info['name'];
            session($session_info);
            unset($user_info['password']);
            return $this->message('1020','登录成功',['data'=>$user_info]);
        }

        return $this->message('1023','用户名或密码错误');
    }
    public function user_info($info){
        if(!isset($info['id'])){
            return $this->message('1021','信息不完整');
        }
        $user_info = $this->user_repo->get_by_where(['id'=>$info['id']]);

        unset($user_info['password']);
        return $this->message('1020','获取成功',['data'=>$user_info]);
    }

    //将密码hash加密
    private function hash($password)
    {
        return md5($this->salt . $password);
    }

    public function logout()
    {
        return $this->message('1030','注销成功');
    }

    public function scan($user){
        if($user==null){
            return 0;
        }
        return $this->user_repo->scan($user);
    }

    public function view()
    {
        $result = $this->user_repo->view();
        return $this->message('1000','获取成功',['data'=>$result]);
    }

    public function access_view($type, $key)
    {
        $result = $this->user_repo->access_view($type,$key);
        return $this->message('1010,','获取成功',['data'=>$result]);
    }

    public function now_view()
    {
        $result = $this->user_repo->now_view();
        return $this->message('1020,','获取成功',['data'=>$result]);
    }

    public function analysis_view($type, $key)
    {
        $result = $this->user_repo->analysis_view($type,$key);
        return $this->message('1010,','获取成功',['data'=>$result]);
    }

    public function add_user($uid, $name)
    {
        if($uid==null){
            $uid = 123456;
        }
        if($name==null){
            return $this->message('1031','未输入姓名');
        }
        $pswd = md5($this->salt . $uid);
        $this->user_repo->add_user($uid,$name,$pswd);
        return $this->message('1030','添加成功');
    }


}